package com.smart.filter;


import com.smart.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * cookie过滤器
 * @author zhanghong
 */
@Slf4j
@Order(-1)
@Component
public class CookieFilter implements Filter {

    @Autowired
    private SessionRepository sessionRepository;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String sessionId = request.getParameter(Constants.SESSIONID);
        if (!StringUtils.isEmpty(sessionId)) {
            // cookie续期
            Session session = sessionRepository.findById(sessionId);
            Cookie cookie = new Cookie(Constants.SESSIONID, sessionId);
            cookie.setPath("/");
            cookie.setMaxAge(86400);
            res.addCookie(cookie);
            req.getSession().setAttribute(Constants.LOGIN_USER, session.getAttribute(Constants.LOGIN_USER));
        }
        chain.doFilter(request, response);
    }

}
